import urllib
from threading import Thread
from PySide6.QtCore import QDir, QFile, QDateTime
from http.server import BaseHTTPRequestHandler, HTTPServer as PyHTTPServer

class HttpServer(object):
    def MakeProxyHTTPRequestHandler(otaDir, logDir, ip, protocolVersion):
        class ProxyHTTPRequestHandler(BaseHTTPRequestHandler):
            def DownloadFile(self, type):
                if not "/OTA/" in self.path:
                    self.send_response(404)
                    self.end_headers()
                    return

                file = QFile(otaDir + "/" + self.path.removeprefix("/OTA/"))
                if file.exists():
                    if type == "GET":
                        if file.open(QFile.ReadOnly):
                            self.send_response(200)
                            self.send_header('Content-type', 'application/octet-stream')
                            self.send_header("Content-Length", str(file.size()))
                            self.end_headers()

                            bytes = file.readAll()
                            self.wfile.write(bytes.data())
                            file.close()
                        else:
                            self.send_response(500)
                    else:
                        self.send_response(200)
                        self.send_header("Content-Type", "application/octet-stream")
                        self.send_header("Content-Length", str(file.size()))
                        self.end_headers()
                else:
                    self.send_response(404)
                    self.send_header("Content-Type", "application/octet-stream")
                    self.send_header("Content-Length", "0")
                    self.end_headers()

            def do_HEAD(self):
                self.protocol_version = protocolVersion
                self.DownloadFile("HEAD")

            def do_GET(self):
                self.protocol_version = protocolVersion
                self.DownloadFile("GET")

            def do_POST(self):
                self.protocol_version = protocolVersion
                if not "/Log" in self.path:
                    self.send_response(404)
                    self.end_headers()
                    return

                if '?' in self.path:#如果带有参数
                    queryString = urllib.parse.unquote(self.path.split('?',1)[1])
                    params = urllib.parse.parse_qs(queryString)

                    deviceId = params["deviceId"][0] if "deviceId" in params else ip
                    fileName = params['fileName'][0] if "fileName" in params else QDateTime.currentDateTime().toString("yyyy-MM-dd_HHmmss") + ".log"

                logPath = logDir + "/[" + deviceId + "]" + fileName
                file = QFile(logPath)
                if file.open(QFile.WriteOnly):
                    self.send_response(200)
                    self.end_headers()

                    datas = self.rfile.read(int(self.headers['content-length']))
                    file.write(datas)
                    file.close()
                else:
                    self.send_response(400)
                    self.end_headers()

        return ProxyHTTPRequestHandler

    def __init__(self):
        self.__PyHttpServer = None

    def __del__(self):
        self.StopServer()
        del self.__thread
        self.__thread = None

    def ServerProcess(self):
        self.__PyHttpServer.serve_forever()

    def StartServer(self, ip, port, otaDir, logDir):
        dir = QDir(logDir)
        if not dir.exists():
            dir.mkpath(dir.absolutePath())

        if (self.__PyHttpServer is not None):
            del self.__PyHttpServer

        self.__PyHttpServer = PyHTTPServer((ip, port), HttpServer.MakeProxyHTTPRequestHandler(otaDir, logDir, ip, "HTTP/1.1"))

        self.__thread = Thread(target=self.ServerProcess)
        self.__thread.start()

        return True

    def StopServer(self):
        if (self.__PyHttpServer is not None):
            self.__PyHttpServer.shutdown()
            self.__PyHttpServer.server_close()
            del self.__PyHttpServer
            self.__PyHttpServer = None
            self.__thread.join()

